package com.mine.redis.util.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author weixiao
 * @date 2024/8/20 14:14
 */
@Service
public class UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void sign(Integer userId) {
        // 拼接key
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + ":" + userId;
        // set bit
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1,true);
    }

    public Integer getSignCount(Integer userId) {
        // 拼接key
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + ":" + userId;
        // 获取整个签到key的值（十进制）
        int dayOfMonth = now.getDayOfMonth();
        // BITFIELD sign:202408:12345 GET u20 0
        List<Long> res = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (CollectionUtils.isEmpty(res)) {
            return 0;
        }
        // 循环判断bitMap上的每一位是不是1
        int count = 0;
        Long bitRes = res.get(0);
        while (true) {
            if ((1 & bitRes) == 1) {
                count++;
                bitRes >>>= 1;
            } else {
                break;
            }
        }
        return count;
    }
}
